package uteis;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;

public class ValidadorCPFCNPJUp implements Validator {

	@Override
	public void validate(FacesContext context, UIComponent componente,
			Object value) throws ValidatorException {
		String cpfOrCnpj = ((String) value).toString();

		String n = cpfOrCnpj.replaceAll("[^0-9]*", "");
		boolean isCnpj = n.length() == 14;
		boolean isCpf = n.length() == 11;

		if (!isCpf && !isCnpj) {
			// return false;
			FacesContext.getCurrentInstance().addMessage(
					null,
					new FacesMessage(FacesMessage.SEVERITY_ERROR, "CPF",
							"CPF invalido."));
			return;
		} else {
			int i;
			int j; // just count
			int digit; // A number digit
			int coeficient; // A coeficient
			int sum; // The sum of (Digit * Coeficient)
			int[] foundDv = { 0, 0 }; // The found Dv1 and Dv2
			int dv1 = Integer
					.parseInt(String.valueOf(n.charAt(n.length() - 2)));
			int dv2 = Integer
					.parseInt(String.valueOf(n.charAt(n.length() - 1)));
			for (j = 0; j < 2; j++) {
				sum = 0;
				coeficient = 2;
				for (i = n.length() - 3 + j; i >= 0; i--) {
					digit = Integer.parseInt(String.valueOf(n.charAt(i)));
					sum += digit * coeficient;
					coeficient++;
					if (coeficient > 9 && isCnpj)
						coeficient = 2;
				}
				foundDv[j] = 11 - sum % 11;
				if (foundDv[j] >= 10)
					foundDv[j] = 0;
			}
			if (!(dv1 == foundDv[0] && dv2 == foundDv[1])) {
				FacesMessage message = new FacesMessage(
						FacesMessage.SEVERITY_ERROR, "LOGIN",
						"CPF/CNPJ invalido.");
				throw new ValidatorException(message);
			}
		}
	}
}
